<?php
require_once ('IOperations.php');
require_once ('AppController.php');



/**
 * @author ValeBonus.com
 * @version 1.0
 * @created 02-dez-2013 23:36:28
 */
class EstablishmentsController extends AppController implements IOperations {

	/**
	 * Set the controller name
	 */
	public $name = 'Establishments';
	
	private function uploadEstablishmentLogo() {			
		// Get the file extension
		$fileExtension = pathinfo($this->request->data['Establishment']['logo']['name'], PATHINFO_EXTENSION);
		
		// There is a file extension
		if ((isset($fileExtension)) && (!(trim($fileExtension) === ''))) {
			// Is a valid file extension
			if (in_array($fileExtension, array("gif", "jpg", "png"))) {
				// Get the uploaded establishment logo
				$file = $this->data['Establishment']['logo'];
			
				// Check errors
				if (($file['size'] > 0) || ($file['error'] === UPLOAD_ERR_OK)) {
					// Check the max file size
					if ($file['size'] < 25001) {
						// Set the absolute path
						$pngAbsoluteFilePath = IMAGES . 'establishmentLogo/' . String::uuid() . '.' . $fileExtension;
							
						// Move the uploaded establishment logo
						if (move_uploaded_file($file['tmp_name'], $pngAbsoluteFilePath)) {
							// Save the absolute file path on the cache
							Cache::write('pngAbsoluteFilePathForEstablishmentLogo', $pngAbsoluteFilePath);
								
							// Provide the return
							return true;
						} else {
							// Show a user message
							$this->Session->setFlash(__('Não foi possível mover o arquivo carregado'), 'flash_error');
						}	
					} else {
						// Show a user message
						$this->Session->setFlash(__('Não foi possível carregar o arquivo. O tamanho do arquivo é de: ' . floor($file['size'] / 1000) . 'KB. O tamanho permitido é de até 25KB'), 'flash_error');
					}
				} else {
					// Show a user message
					$this->Session->setFlash(__('Não foi possível carregar o arquivo'), 'flash_error');
				}
			} else {
				// Show a user message
				$this->Session->setFlash(__('A imagem do tipo .' . $fileExtension . ' não é válida'), 'flash_error');
			}			
		} else {
			// Provide the return
			return true;
		}
						
		// Provide the return
		return false;
	}

	public function index() {
		// Show all elements
		$this->Establishment->recursive = 0;
		$this->set('establishments', $this->paginate());
	}

	public function add() {
		// Load the fields
		$this->set('interest', $this->Establishment->Interest->find('list', array('fields' => array('Interest.id', 'Interest.name'))));
		
		// Check if the request is an post http method
		if ($this->request->is('post')) {
			// Create the establishment
			$this->Establishment->create();
		
			// Upload establishment logo and check the result
			if ($this->uploadEstablishmentLogo()) {
				// Persist the establishment
				if ($this->Establishment->save($this->request->data)) {
					// Show a user message
					$this->Session->setFlash(__('O estabelecimento foi salvo'), 'flash_success');
			
					// Redirect to the index function
					$this->redirect(array('action' => 'index'));
				} else {
					// Show a user message
					$this->Session->setFlash(__('O estabelecimento não pode ser salvo. Por favor, tente de novo'), 'flash_error');
				}
			}
		}
	}

	/**
	 * 
	 * @param id    The Establishment Id
	 */
	public function edit($id) {
		// Load the fields
		$this->set('interest', $this->Establishment->Interest->find('list', array('fields' => array('Interest.id', 'Interest.name'))));
		
		// Set the establishment id
		$this->Establishment->id = $id;
		
		// Check if the establishment exists
		if (!($this->Establishment->exists())) {
			// Throw an exception
			throw new NotFoundException(__('Estabelecimento inválido'));
		}
		
		// Check if it is a post or a put http method
		if ($this->request->is('post') || $this->request->is('put')) {
			// Upload establishment logo and check the result
			if ($this->uploadEstablishmentLogo()) {
				// Persist the establishment
				if ($this->Establishment->save($this->request->data)) {
					// Show a user message
					$this->Session->setFlash(__('O estabelecimento foi salvo'), 'flash_success');
				
					// Redirect to the index function
					$this->redirect(array('action' => 'index'));
				} else {
					// Show a user message
					$this->Session->setFlash(__('O estabelecimento não pode ser salvo. Por favor, tente de novo'), 'flash_error');
				}
			}						
		} else {
			// Retreive the requested data
			$this->request->data = $this->Establishment->read(null, $id);
		
			// Clear the data
			//unset($this->request->data['Establishment']['']);
		}
	}

	/**
	 * 
	 * @param id    The Establishment Id
	 */
	public function delete($id) {
		// Check if the request is an post http method
		if (!$this->request->is('post')) {
			// Throw an exception
			throw new MethodNotAllowedException();
		}
		
		// Set the establishment id
		$this->Establishment->id = $id;
		
		// Check if the establishment exists
		if (!$this->Establishment->exists()) {
			// Throw an exception
			throw new NotFoundException(__('Estabelecimento inválido'));
		}
		
		// Delete the establishment
		if ($this->Establishment->delete()) {
			// Show a user message
			$this->Session->setFlash(__('Estabelecimento apagado'), 'flash_success');
		
			// Redirect to the index function
			$this->redirect(array('action' => 'index'));
		}
		
		// Show a user message
		$this->Session->setFlash(__('O estabelecimento não foi apagado'), 'flash_error');
		
		// Redirect to the index function
		$this->redirect(array('action' => 'index'));
	}

	/**
	 * 
	 * @param id    The Establishment Id
	 */
	public function view($id) {
		// Set the id to the establishment object
		$this->Establishment->id = $id;
		
		// Check if the establishment exists
		if (!($this->Establishment->exists())) {
			// Throw an exception
			throw new NotFoundException(__('Estabelecimento inválido'));
		}
		
		// Read the establishment object properties and show them
		$this->set('establishment', $this->Establishment->read(null, $id));
	}

	public function jsonlist() {
		// To disable the layout
		$this->layout = null;
		
		// Set the json content to the json object
		$this->set('json', $this->Establishment->find('all'));
		
		// Call the view
		$this->render('../Elements/json');
	}
	
	/**
	 *
	 * @param id    The Establishment Id
	 */
	public function jsonview($id) {
		// To disable the layout
		$this->layout = null;
	
		// Set the id to the user object
		$this->Establishment->id = $id;
	
		// Check if the user exists
		if (!($this->Establishment->exists())) {
			// Throw an exception
			throw new NotFoundException(__('Estabelecimento inválido'));
		}
	
		// Set the json content to the json object
		$this->set('json', $this->Establishment->read(null, $id));
	
		// Call the view
		$this->render('../Elements/json');
	}
	
	/**
	 *
	 * @param id    The Interest Id
	 */
	public function jsonqueryperinterest($interest_id) {
		// To disable the layout
		$this->layout = null;
		
		// Set the json content to the json object
		$this->set('json', $this->Establishment->find('all', array('conditions' => array('Establishment.interest_id' => $interest_id))));
		
		// Call the view
		$this->render('../Elements/json');
	}	

}
?>